package com.szp.lg.blog.interceptor;

import com.alibaba.fastjson.JSON;
import com.szp.lg.blog.config.props.DataSourceProps;
import com.szp.lg.blog.constant.ConstantDbZkPath;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

import java.io.IOException;
import java.util.Optional;
import java.util.Properties;

public class PropertyInterceptor extends PropertySourcesPlaceholderConfigurer {
//    zk.url=127.0.0.1:2181
//zk.timeout=1000
//zk.retry=3

    //    spring.datasource.url=jdbc:mysql://localhost:3306/blog_system?serverTimezone=UTC
//    spring.datasource.username=root
//    spring.datasource.password=123456
    @Override
    protected Properties mergeProperties() throws IOException {
        Properties result = super.mergeProperties();
        Optional<String> zkUrl = Optional.of((String) result.get("zk.url"));
        Optional<Integer> zkTimeout = Optional.of(Integer.parseInt((String)result.get("zk.timeout")));
        Optional<Integer> zkRetry = Optional.of(Integer.parseInt((String)result.get("zk.retry")));

        DataSourceProps dataSourceProps = getDbInfoFromZk(zkUrl.orElse("127.0.0.1:2181"),
                zkTimeout.orElse(3000), zkRetry.orElse(3));

        if (null != dataSourceProps) {
            result.put("spring.datasource.url", dataSourceProps.getUrl());
            result.put("spring.datasource.username", dataSourceProps.getUsername());
            result.put("spring.datasource.password", dataSourceProps.getPassword());
        }
        return result;
    }

    private DataSourceProps getDbInfoFromZk(String zkUrl, Integer zkTimeout, Integer zkRetry) {
        //curator创建
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(zkTimeout, zkRetry);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(zkUrl, retryPolicy);
        curatorFramework.start();
//默认数据源
        DataSourceProps prop = new DataSourceProps();
        prop.setUrl("jdbc:mysql://localhost:3306/blog_system?serverTimezone=UTC");
        prop.setUsername("root");
        prop.setPassword("123456");


        String path = ConstantDbZkPath.DB_ZK_PATH;
        byte[] ret = null;
        try {
            ret = curatorFramework.getData().forPath(path);


        } catch (Exception e) {
            e.printStackTrace();
            logger.info("从zk获取数据库信息失败", e);
            if (null == ret) {
                //TODO 创建节点
                String propStr = JSON.toJSONString(prop);
                try {
                    String dataPath = curatorFramework.create().creatingParentsIfNeeded().forPath(path, propStr.getBytes());
                    ret = curatorFramework.getData().forPath(path);
                } catch (Exception ex) {
                    logger.info("数据库信息节点zk不存在，使用默认本地数据库创建节点" + propStr);
                    ex.printStackTrace();
                }
                logger.info("使用写死的数据源");
                logger.info("数据库信息节点zk不存在，使用默认本地数据库创建节点" + propStr);
            }
        }
        String dataSource = new String(ret);
        DataSourceProps dataSourceProps = JSON.parseObject(dataSource, DataSourceProps.class);
        return dataSourceProps;

    }
}
